package com.hellobike.haxing.modules.supplier.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hellobike.haxing.common.util.PasswordUtil;
import com.hellobike.haxing.common.util.oConvertUtils;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.supplier.entity.TSupplier;
import com.hellobike.haxing.modules.supplier.mapper.TSupplierMapper;
import com.hellobike.haxing.modules.supplier.service.ITSupplierService;
import com.hellobike.haxing.modules.system.entity.SysDepartRole;
import com.hellobike.haxing.modules.system.entity.SysUser;
import com.hellobike.haxing.modules.system.entity.SysUserRole;
import com.hellobike.haxing.modules.system.mapper.SysDepartRoleMapper;
import com.hellobike.haxing.modules.system.mapper.SysUserRoleMapper;
import com.hellobike.haxing.modules.system.service.ISysUserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description: t_supplier
 * @Author: haxing-boot
 * @Date: 2020-01-09
 * @Version: V1.0
 */
@Service
public class TSupplierServiceImpl extends ServiceImpl<TSupplierMapper, TSupplier> implements ITSupplierService {

    @Autowired
    private TSupplierMapper supplierMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private SysDepartRoleMapper sysDepartRoleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> saveSupplier(TSupplier tSupplier) {
        Result<?> result = new Result<>();
        SysUser sysUser = sysUserService.getUserByPhone(tSupplier.getMobile());
        if (sysUser != null) {
            return result.error500("手机号已经存在，请更换手机号");
        }
        Integer count = supplierMapper.selectCount(new QueryWrapper<TSupplier>().lambda().eq(TSupplier::getMobile, tSupplier.getMobile()));
        if (count > 1) {
            return result.error500("手机号已经存在，请更换手机号");
        }
        supplierMapper.insert(tSupplier);
        sysUser = new SysUser();
        sysUser.setUsername(tSupplier.getMobile());
        sysUser.setRealname(tSupplier.getRealName());
        sysUser.setPassword("123456");
        sysUser.setWorkNo(RandomStringUtils.random(7, false, true));
        String salt = oConvertUtils.randomGen(8);
        sysUser.setSalt(salt);
        String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), sysUser.getPassword(), salt);
        sysUser.setPassword(passwordEncode);
        sysUserService.save(sysUser);
        List<SysDepartRole> departRoleList = sysDepartRoleMapper
                .selectList(new QueryWrapper<SysDepartRole>().lambda().eq(SysDepartRole::getDepartId, tSupplier.getDepartId()));
        if (!CollectionUtils.isEmpty(departRoleList)) {
            for (SysDepartRole sysDepartRole : departRoleList) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(sysDepartRole.getRoleId().intValue());
                sysUserRole.setUserId(sysUser.getId());
                sysUserRoleMapper.insert(sysUserRole);
            }
        }

        return result;
    }

    @Override
    public Result<?> updateSupplier(TSupplier tSupplier) {
        Result<?> result = new Result<>();
        SysUser sysUser = sysUserService.getUserByPhone(tSupplier.getMobile());
        TSupplier origin = supplierMapper.selectById(tSupplier.getId());
        if (origin == null) {
            return result.error500("供应商不存在");
        }
        /**
         * 修改手机，重新创建账号
         */
        if (!origin.getMobile().equals(tSupplier.getMobile())) {
            if (sysUser != null) {
                return result.error500("手机号已经存在，请更换手机号");
            }
            Integer count = supplierMapper.selectCount(new QueryWrapper<TSupplier>().lambda().eq(TSupplier::getMobile, tSupplier.getMobile()));
            if (count > 1) {
                return result.error500("手机号已经存在，请更换手机号");
            }
            supplierMapper.insert(tSupplier);
            sysUser = new SysUser();
            sysUser.setUsername(tSupplier.getMobile());
            sysUser.setPassword("123456");
            sysUser.setWorkNo(RandomStringUtils.random(7, false, true));
            sysUser.setRealname(tSupplier.getRealName());
            String salt = oConvertUtils.randomGen(8);
            sysUser.setSalt(salt);
            String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), sysUser.getPassword(), salt);
            sysUser.setPassword(passwordEncode);
            sysUserService.save(sysUser);
        }
        /**
         * 删除旧的默认权限
         */
        sysUserRoleMapper.delete(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, sysUser.getId()));
        /**
         * 重新授权
         */
        List<SysDepartRole> departRoleList = sysDepartRoleMapper
                .selectList(new QueryWrapper<SysDepartRole>().lambda().eq(SysDepartRole::getDepartId, tSupplier.getDepartId()));
        if (!CollectionUtils.isEmpty(departRoleList)) {
            for (SysDepartRole sysDepartRole : departRoleList) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(sysDepartRole.getRoleId().intValue());
                sysUserRole.setUserId(sysUser.getId());
                sysUserRoleMapper.insert(sysUserRole);
            }
        }
        return result;
    }

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
}
